package com.hp.bon.sgw.wh.channel.groupConsistency;

import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.hp.bon.sgw.bean.XmlMessage;
import com.hp.bon.sgw.core.channel.SoapChannel;
import org.simpleframework.http.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;
import com.hp.bon.sgw.wh.channel.common.BizConsts;
import com.hp.bon.sgw.wh.channel.common.BizParam;
import com.hp.bon.sgw.wh.channel.common.BizResult;

public class ConsistencyResponsor {

	private static final Logger _log = LoggerFactory.getLogger(ConsistencyResponsor.class);

	public void doResponse(BizResult bizResult, Response response) {

		try {
			PrintStream body = response.getPrintStream();
			byte[] resps = bizResult.getHttpBody().getBytes("UTF-8");
			body.write(resps);
			body.close();
		} catch (Exception e) {
			_log.error(e.getMessage(), e);
		}

	}
	
	public void doExceptionResponse(Response response, String failedCode, String failedReason) {
		try {
			PrintStream body = response.getPrintStream();
			Map<String, String> data = new HashMap<String, String>();			
			data.put("resultCode", failedCode);
			data.put("resultMsg", failedReason);

			Gson gson = new Gson();
			String respXML = gson.toJson(data);
			body.write(respXML.getBytes("UTF-8"));
			body.close();
		} catch (Exception e) {
			_log.error("TMallChannel errorAck error, msg = {}", e.getMessage());
            _log.error("",e);
		}
	}

	public void doResponseWSError(Response response, String mid, int retCode, String errMsg) {

		PrintStream printStream = null;
		try {
			printStream = response.getPrintStream();
		} catch (Exception e) {
			_log.error("response fail! mid={}", mid);
			_log.error(e.getMessage(), e);
			return;
		}

		try {
			XmlMessage ack = new XmlMessage(false);
			ack.setMID(mid);
			ack.setRTT(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(Long.valueOf(System.currentTimeMillis())));
			ack.setRC(Integer.toString(retCode));
			ack.setDS(errMsg);

			_log.error(JSON.toJSONString(ack));

			SoapChannel.directAck(ack, printStream);

			_log.error("direct ack, mid={}", mid);
		} catch (Exception e) {
			_log.error(e.getMessage(), e);
		}

	}

	public boolean checkParamAndDoResponse(Response response, BizParam bizParam) {
		String requestPath = bizParam.getParamString(BizConsts.KEY_REQUEST_PATH);
		_log.info("requestPath={}", requestPath);
		
		//TODO ......
		
		// 如果参数校验正常，则返回true
		return true;
	}

}
